package org.example;

import java.sql.*;
import java.util.*;

public class DBUtil {
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public static String url = "jdbc:mysql://localhost:3306/Chistory";
    public static String uid = "root";
    public static String pwd = "123456";

    public static Connection getConn() throws SQLException {
        return DriverManager.getConnection(url, uid, pwd);
    }

    public static void closeConn(Connection conn, PreparedStatement ps, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (ps != null) ps.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static int executeUpdate(String sql) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConn();
            ps = conn.prepareStatement(sql);
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConn(conn, ps, null);
        }
        return -1;
    }

    public static int executePreparedUpdate(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConn();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            return ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConn(conn, ps, null);
        }
        return -1;
    }

    public static List<chatmessages> getUsers() {
        List<chatmessages> userList = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConn();
            String sql = "SELECT UserName, MessageText FROM chatmessages";
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                String UserName = rs.getString("UserName");
                String MessageText = rs.getString("MessageText");
                chatmessages user = new chatmessages(UserName, MessageText);
                userList.add(user);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeConn(conn, ps, rs);
        }
        return userList;
    }
}
